<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test.js"></script>
<script src="../resources/common.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
description("Test unwrapping an HKDF key");

jsTestIsAsync = true;

kHkdfKey = hexStringToUint8Array("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
kIv = new Uint8Array(16);

var derivingKeyAlgorithm = {
    name: "HKDF",
    hash: "SHA-256",
    salt: new Uint8Array(),
    info: new Uint8Array()
};

Promise.resolve(null).then(function(result) {
    // Create a key to use for wrapping/unwrapping
    return crypto.subtle.generateKey({name: "AES-GCM", length: 256}, false, ['encrypt', 'unwrapKey']);
}).then(function(result) {
    wrappingKey = result;

    shouldEvaluateAs("wrappingKey.algorithm.name", "AES-GCM");
    shouldEvaluateAs("wrappingKey.extractable", false);
    shouldEvaluateAs("wrappingKey.usages.join(',')", "encrypt,unwrapKey");

    // Wrap the HKDF key. Since the HKDF algorithm does not support the export
    // key operation, it is wrapped by calling encrypt.
    return crypto.subtle.encrypt({name: "AES-GCM", length: 256, iv: kIv}, wrappingKey, kHkdfKey);
}).then(function(result) {
    wrappedKey = result;

    // Unwrap it as a raw key.
    return crypto.subtle.unwrapKey("raw", wrappedKey, wrappingKey, {name: "AES-GCM", length: 256, iv: kIv}, "HKDF", false, ['deriveBits']);
}).then(function(result) {
    unwrappedHkdfKey = result;

    shouldEvaluateAs("unwrappedHkdfKey.algorithm.name", "HKDF");
    shouldEvaluateAs("unwrappedHkdfKey.extractable", false);
    shouldEvaluateAs("unwrappedHkdfKey.usages.join(',')", "deriveBits");

    debug("\nUnwrap an HKDF key using pkcs8 as the format.");
    return crypto.subtle.unwrapKey("pkcs8", wrappedKey, wrappingKey, {name: "AES-GCM", length: 256, iv: kIv}, "HKDF", false, ['deriveBits']);
}).then(failAndFinishJSTest, function(result) {
    logError(result);
}).then(finishJSTest, failAndFinishJSTest);

</script>

</body>
</html>
